<template>
  <div>
    <template v-if="isSort">
      <!-- 按钮 -->
      <el-button style="margin:10px 10px" type="primary" icon="el-icon-refresh-right" circle
        @click="getBannerImages"></el-button>
      <el-button type="primary" icon="el-icon-plus" style="margin:10px" @click="getShow">添加</el-button>
      <el-button type="info" icon="el-icon-d-caret" style="margin:10px 0" @click="isSort = false;">排序</el-button>
      <!-- 表格 -->
      <el-table style="width: 100%;" border :data="list">
        <el-table-column prop="id" label="id" width="80" align="center">
        </el-table-column>
        <el-table-column prop="picName" label="名称" width="200" align="center">
        </el-table-column>
        <el-table-column label="图片" align="center" width="200">
          <template slot-scope="{ row, $index }">
            <el-image style="width: 60px; height: 60px" :src="$staticURL+row.picSrc" >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="linkUrl" label="链接地址" align="center">
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="{ row, $index }">
            <!-- <el-button type="primary" icon="el-icon-edit" circle></el-button> -->
            <el-tooltip content="修改轮播图" placement="top" slot="reference">
              <el-button type="primary" icon="el-icon-edit" @click="ubpateBannar(row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除轮播图" placement="top" slot="reference">
              <el-button type="danger" icon="el-icon-delete" @click="delBannar(row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 对话框  -->
      <el-dialog :title="state ? '添加轮播图' : '修改轮播图'" :visible.sync="dialogFormVisible">
        <el-form style="width:80%" :model="tmFrom" :rules="rules" ref="ruleForm">
          <el-form-item label="轮播图名称" label-width="100px" prop="picName">
            <el-input autocomplete="off" v-model="tmFrom.picName"></el-input>
          </el-form-item>
          <el-form-item label="跳转链接" label-width="100px">
            <el-input autocomplete="off" v-model="tmFrom.linkUrl" placeholder="填写跳转的页面链接或网站链接，非必填"></el-input>
          </el-form-item>
          <!-- 上传图片 -->
          <el-form-item label='头像上传' label-width="100px">
            <el-upload class="avatar-uploader" action='#' :on-preview="handlePictureCardPreview" :on-change="uploadFile"
              :auto-upload="false" :show-file-list='false'>

              <i v-if="imageUrl1" class="el-icon-circle-close " @click.stop="handleRemove1"></i>
              <i v-if="imageUrl1" class="el-icon-zoom-in " @click.stop="handlePictureCardPreview"></i>


              <img v-if='imageUrl1' :src='imageUrl1' class='avatar' :show-file-list='false'>
              <i v-else class='el-icon-plus avatar-uploader-icon'></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
              <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
            </el-dialog>
          </el-form-item>
       <!--   <el-form-item label="上传图片" label-width="100px" prop="picSrc">
            <el-upload class="avatar-uploader" action="https://api.yushiai.com.cn/biz/uploadImgage" :headers="headers"
              name="image" :show-file-list="false" :on-success="handleAvatarSuccess">
              <img v-if="tmFrom.picSrc" :src="tmFrom.picSrc" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png文件</div>
            </el-upload>
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="getAddBannerImage" v-if="state">确 定</el-button>
          <el-button type="primary" @click="aa()" v-else>修改</el-button>
        </div>
      </el-dialog>
    </template>

    <template v-else>
      <div style="margin:30px">
        <el-tree :data="list" node-key="id" ref="tree" :props="defaultProps" @node-drag-start="handleDragStart"
          @node-drag-enter="handleDragEnter" @node-drag-leave="handleDragLeave" @node-drag-end="handleDragEnd"
          @node-drop="handleDrop" draggable :allow-drop="allowDrop" :allow-drag="allowDrag">
        </el-tree>
      </div>

      <div style="margin:40px 20px 20px 20px">
        <el-button type="primary">确认</el-button>
        <el-button type="danger" @click="isSort = true">取消</el-button>
      </div>
    </template>
  </div>
</template>

<script>
    import axios from 'axios'
import { getToken } from '@/utils/auth'
export default {
  name: 'Bannar',
  data() {
    return {
      // 对话框显示与隐藏控制
      dialogFormVisible: false,
      // 表单对象
      tmFrom: {
        picName: '',
        linkUrl: '',
        picSrc: ''
      },
      dialogVisible: false,
      dialogImageUrl: '',
      imageUrl1:'',
      //列表数据
      list: [
        // {
        //   "createId": 1,
        //   "createTime": "2023-01-09 19:55:46",
        //   "id": 4,
        //   "linkUrl": "https://www.baidu.com",
        //   "picName": "网易云音乐",
        //   "picSrc": "http://192.168.0.106:2020/static/pic/1957007149.jpg",
        //   "rankId": 3
        // },
        // {
        //   "createId": 1,
        //   "createTime": "2023-01-09 20:11:23",
        //   "id": 5,
        //   "linkUrl": "123123",
        //   "picName": "网易",
        //   "picSrc": "http://192.168.0.106:2020/static/pic/1957012899.jpg",
        //   "rankId": 4
        // },
        // {
        //   "createId": 1,
        //   "createTime": "2023-01-10 17:35:17",
        //   "id": 7,
        //   "linkUrl": "",
        //   "picName": "HAHAH",
        //   "picSrc": "http://192.168.0.106:2020/static/pic/1957008589.jpg",
        //   "rankId": 5
        // }
      ],
      // 当前为修改还是添加 修改为false 添加为true
      state: true,
      // 排序
      isSort: true,
      // 表单验证
      rules: {
        picName: [
          { required: true, message: '请输入轮播图名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' }
        ],
        picSrc: [
          { required: true, message: '请选择轮播图图片' }
        ]
      },
      defaultProps: {
        label: 'picName'
      }
    }
  },
  mounted() {
    this.getBannerImages()
  },
  computed: {
    headers() {
      return {
        'session_token': getToken()
      };
    }
  },
  methods: {

    // 删除只需清空imageUrl1即可
    handleRemove1(file, fileList) {
      // console.log(file, fileList);
      this.imageUrl1 = "";
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = this.imageUrl1;
      this.dialogVisible = true;
    },
    uploadFile(item) {
      console.log(item);
      let formData = new FormData();
      let file = item.raw;
      this.imageUrl1 = URL.createObjectURL(file);
      formData.append("image", file);
      this.formData = formData
      console.log(file, "216")
    },

    aa() {
      // console.log(this.tmFrom)
      //   return false;
      if(this.imageUrl1 == ""){
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            let res = await this.$API.system.getAlterBannerImage(this.tmFrom);
            this.dialogFormVisible = false;
            this.getBannerImages()
              this.imageUrl1 = "";
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      }else{
        axios({
        method: "post",
        url: "https://api.yushiai.com.cn/biz/uploadImgage",
        data: this.formData,
        headers: {
          'session_token': getToken(),
          'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryLOZf2MbOw2wkMpjv'
        },
      }).then((res) => {
        console.log(res)
        if (res.data.code == 200) {
          console.log(res.data.data.imgageUrl)
          this.tmFrom.picSrc = res.data.data.imgageUrl
          console.log(this.tmFrom)
          this.$refs.ruleForm.validate(async (valid) => {
            if (valid) {
              let res = await this.$API.system.getAlterBannerImage(this.tmFrom);
              this.dialogFormVisible = false;
              this.getBannerImages()
              this.imageUrl1 = "";
            } else {
              console.log('error submit!!');
              return false;
            }
          })
        }
      })
      }

      // let res = this.$API.question.uploadImgage({
      //   image: this.formData
      // })
      // console.log(res)
    },

    // 所有轮播图
    async getBannerImages() {
      let res = await this.$API.system.getBannerImages()
      console.log(res)
      this.list = res.data
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.tmFrom.picSrc = res.data.imgageUrl;
    },
    // 取消
    getShow() {
      this.state = true
      this.dialogFormVisible = true
      this.tmFrom = {
        picName: '',
        linkUrl: '',
        picSrc: ''
      }
    },
    // 添加
    getAddBannerImage() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let res = await this.$API.system.getAddBannerImage(this.tmFrom);
          this.dialogFormVisible = false;
          this.getBannerImages();
            this.imageUrl1 = "";
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    // 点击修改
    ubpateBannar(row) {
      this.state = false
      this.dialogFormVisible = true;
      // 浅拷贝  让tmFrom收到的数据非服务器直接传回的数据
      this.tmFrom = { ...row };
    },
    // 点击修改
    getAlterBannerImage() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let res = await this.$API.system.getAlterBannerImage(this.tmFrom);
          this.dialogFormVisible = false;
          this.getBannerImages();
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    // 删除
    async delBannar(id) {
      let res = await this.$API.system.getDeleteBanner({ id: id });
      this.getBannerImages();
    },
    handleDragStart(node, ev) {
      console.log(1);
    },
    handleDragEnter(draggingNode, dropNode, ev) {
      console.log(2);
    },
    handleDragLeave(draggingNode, dropNode, ev) {
      console.log(3);
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      console.log(5);
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log(6);
    },
    allowDrop(draggingNode, dropNode, type) {
      console.log(dropNode)
      // if (dropNode.data.label === '二级 3-1') {
      //   return type !== 'inner';
      // } else {
      //   return true;
      // }
    },
    allowDrag(draggingNode) {
      console.log(draggingNode.key)
      return true
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
